package com.siashan.toolkit.crypt;

import java.security.Provider;

/**
 * 全局单例的 org.bouncycastle.jce.provider.BouncyCastleProvider 对象
 *
 * @author siashan
 * @since 1.0.7
 */
public enum BouncyCastleProvider {
    /**
     * 实例
     */
    INSTANCE;

    private Provider provider;
    private static boolean useBouncyCastle = true;

    BouncyCastleProvider() {
        try {
            this.provider = createBouncyCastleProvider();
        } catch (NoClassDefFoundError e) {
            // 异常说明未引用bcprov-jdk15to18库，不做处理
        }
    }

    /**
     * 获取{@link Provider}
     * @return {@link Provider}
     */
    public Provider getProvider() {
        return useBouncyCastle ? this.provider : null;
    }

    /**
     * 设置是否使用Bouncy Castle库<br>
     * 如果设置为false，表示强制关闭Bouncy Castle而使用JDK
     *
     * @param isUseBouncyCastle 是否使用BouncyCastle库
     */
    public static void setUseBouncyCastle(boolean isUseBouncyCastle) {
        useBouncyCastle = isUseBouncyCastle;
    }


    /**
     * 创建Bouncy Castle 提供者<br>
     * 如果用户未引入bouncycastle库，则此方法抛出{@link NoClassDefFoundError} 异常
     *
     * @return {@link Provider}
     */
    private Provider createBouncyCastleProvider() {
        return new org.bouncycastle.jce.provider.BouncyCastleProvider();
    }
}
